package ldh.im.dto.codec.binery;

import io.netty.buffer.ByteBuf;
import ldh.im.dto.base.Message;
import ldh.im.dto.business.P2pTextMessage;
import ldh.im.dto.business.ServerRedirectMessage;
import ldh.im.dto.base.Dto;
import ldh.im.dto.codec.CodecFactory;

public class ServerRedirectMessageCodec extends AckToCodec<ServerRedirectMessage> {

    @Override
    public void encode(ServerRedirectMessage serverRedirectMessage, ByteBuf byteBuf) {
        TransferCode transferCode = CodecFactory.getInstance().getTransfer(serverRedirectMessage.getMessage().getClass(), serverRedirectMessage.getCodecType());
        byteBuf.writeShort(transferCode.getCode());
        ByteBuf dataByteBuf = (ByteBuf) transferCode.getImCoder().encode(serverRedirectMessage.getMessage());
        byteBuf.writeBytes(dataByteBuf);
    }

    @Override
    public void decode(ServerRedirectMessage serverRedirectMessage, ByteBuf byteBuf) {
        short code = byteBuf.readShort();
        TransferCode transferCode = CodecFactory.getInstance().getTransfer(code);
        Dto dto = transferCode.getImCoder().decode(byteBuf);
        serverRedirectMessage.setMessage((P2pTextMessage) dto);
    }

    @Override
    public ServerRedirectMessage create() {
        return new ServerRedirectMessage();

    }
}
